package net.csdra.libraryborrowing.service.user;

import net.csdra.libraryborrowing.domain.user.User;
import net.csdra.libraryborrowing.domain.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.nio.file.AccessDeniedException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by msf on 2017/10/11.
 */
@Service
public class CurrentUserInfoImpl implements CurrentUserInfo<CurrentUserInfoImpl.UserForm> {

    final UserRepository userRepository;

    @Autowired
    public CurrentUserInfoImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserForm set(UserForm user) {
        user.setPassword("");
        System.out.println("CurrentUserInfo init");
        List<SimpleGrantedAuthority> collect = user.getAuthoritys().stream().map(userAuthoritys -> {
            return new SimpleGrantedAuthority("ROLE_" + userAuthoritys);
        }).collect(Collectors.toList());
        Authentication authentication = new UsernamePasswordAuthenticationToken(user.getId(), user, collect);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return user;
    }

    @Override
    public UserForm get() throws AccessDeniedException {
        try {
            UserForm userForm = (UserForm) SecurityContextHolder.getContext().getAuthentication().getCredentials();
            return userForm;
        }catch (Exception e){
            throw new AccessDeniedException("需要登录");
        }
    }

    class UserForm extends User {

    }
}
